package util;

import ejb.facades.TripFacadeLocal;
import ejb.facades.UserFacadeLocal;
import entities.Trip;
import entities.extra.UserTripParticipation;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.Singleton;

/**
 * Trabalho PD - 2014/2015
 *
 * @author a21210380 a21210392
 */
@Singleton
public class CloseTrips {

    @EJB
    private Clock clock;

    @EJB
    private TripFacadeLocal tripFacadeLocal;

    @EJB
    private UserFacadeLocal userFacade;

    @Schedule(minute = "*/1", hour = "*")
    public void update() {
        List<Trip> findUnfinishedTrips = tripFacadeLocal.findUnfinishedTrips();
        for (Trip p : findUnfinishedTrips) {
            if (p.getArrivalEstimatedDate().before(clock.getTime())) {
                p.endTrip();
                for (UserTripParticipation utp : p.getParticipations()) {
                    if (utp.getAccepted()) {
                        utp.getUser().addToEvaluation(p);
                        p.addToEvaluation(utp.getUser());
                        userFacade.edit(utp.getUser());
                    }
                }
                tripFacadeLocal.edit(p);
            }
        }
    }

}
